from flask import Flask, request, jsonify, send_file, g
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
import datetime
import sqlite3
import json
from functools import wraps
# 【已增加】导入你的算法所需的库
import pandas as pd
import numpy as np
import re, math
from EmbeddingSearchEngine import EmbeddingSearchEngine
import base64
from get_interests import *
from username2id import get_user_id_from_username

# Flask 配置
app = Flask(__name__)
app.secret_key = 'nj_travel_secret_key_2025'
CORS(app)

DATABASE = 'jiangsu.db'
search_engine = EmbeddingSearchEngine(
    model_dir="./bert_finetune/optimized_dual_relation_bert",
    db_path="jiangsu.db"
)

current_username = None
# ================= 从 Valid.py 移植的工具函数 =================
def clean_text(text):
    return re.sub(r"[^\u4e00-\u9fa5a-zA-Z0-9\s]", "", str(text))

# 广告类关键词
def has_ad_keywords(text):
    kws = ["合作","推广","折扣","代购","团购","广告","赞助","私信","软文","接待"]
    return any(k in str(text) for k in kws)

# 简单情感分析（正负词词典）
pos_words = ["好","喜欢","推荐","不错","美","开心","棒","值得","赞","舒服","治愈","划算","开心"]
neg_words = ["坑","差","糟糕","失望","太贵","一般","不推荐","差评","难吃","累","排队","遗憾"]

def sentiment_score(text):
    t = str(text)
    if t.strip() == "":
        return 0.5
    pc = sum(t.count(w) for w in pos_words)
    nc = sum(t.count(w) for w in neg_words)
    return (pc + 1) / (pc + nc + 2)  # 拉普拉斯平滑

# 文本打分：增加攻略优先级
def compute_text_score(row):
    text = row['text_clean']
    base = row['sentiment'] if not pd.isna(row['sentiment']) else 0.5
    
    # 广告类 → 扣分
    if has_ad_keywords(text):
        base *= 0.6
    
    # 攻略/推荐类 → 强力加分（最低保证 0.75）
    strategy_kws = ["攻略","路线","交通","门票","行程","住宿","注意事项","玩法","推荐","体验","游玩"]
    if any(k in text for k in strategy_kws):
        base = max(base, 0.75)
    
    # 避雷/不要买 → 额外加分
    if "避雷" in text or "不要" in text:
        base = min(1.0, base + 0.2)
    
    return min(1.0, base)

# ================= 数据库连接 =================
def get_db_connection():
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn

def get_user_by_username(username):
    conn = get_db_connection()
    user = conn.execute('SELECT * FROM users WHERE username = ?', (username,)).fetchone()
    conn.close()
    return user

# ================= JWT 校验 =================
def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.headers.get('Authorization')
        if not token:
            return jsonify({'success': False, 'message': '请先登录'}), 401
        try:
            if token.startswith('Bearer '):
                token = token[7:]
            data = jwt.decode(token, app.secret_key, algorithms=['HS256'])
            current_user = data['user']
        except jwt.ExpiredSignatureError:
            return jsonify({'success': False, 'message': 'Token 过期'}), 401
        except jwt.InvalidTokenError:
            return jsonify({'success': False, 'message': 'Token 无效'}), 401
        return f(current_user, *args, **kwargs)
    return decorated

# 辅助函数：尝试从Token获取用户，不存在或无效时不报错，返回None
def get_user_from_token():
    token = request.headers.get('Authorization')
    if token and token.startswith('Bearer '):
        try:
            token = token[7:]
            data = jwt.decode(token, app.secret_key, algorithms=['HS256'])
            return get_user_by_username(data['user'])
        except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
            return None
    return None

# ================= 前端页面 =================
@app.route('/')
def index():
    return send_file("小小红书.html")

# ================= API (用户认证) =================
# ... (此部分代码未改变，保持原样)
@app.route('/api/register', methods=['POST'])
def register():
    data = request.get_json()
    username, password = data.get('username'), data.get('password')
    name = data.get('name') or username
    if not username or not password:
        return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
    conn = get_db_connection()
    exist = conn.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone()
    if exist:
        conn.close()
        return jsonify({'success': False, 'message': '用户名已存在'}), 400
    hashed = generate_password_hash(password)
    conn.execute('INSERT INTO users (username,password,name) VALUES (?,?,?)',
                 (username, hashed, name))
    conn.commit()
    conn.close()
    
    token = jwt.encode(
        {'user': username, 'exp': datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=24)},
        app.secret_key, algorithm='HS256'
    )
    return jsonify({
        'success': True, 
        'message': '注册成功，已自动登录', 
        'name': name,
        'token': token,
        'has_preferences': False
    })

@app.route('/api/login', methods=['POST'])
def login():
    data = request.get_json()
    username, password = data.get('username'), data.get('password')
    conn = get_db_connection()
    user_record = conn.execute('SELECT * FROM users WHERE username=?', (username,)).fetchone()
    
    if not user_record:
        conn.close()
        return jsonify({'success': False, 'message': '用户不存在'}), 401
        
    if check_password_hash(user_record['password'], password):
        user_id = user_record['id']
        preferences = conn.execute('SELECT 1 FROM user_preferences WHERE user_id = ?', (user_id,)).fetchone()
        has_preferences = bool(preferences)
        conn.close()

        token = jwt.encode(
            {'user': username, 'exp': datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=24)},
            app.secret_key, algorithm='HS256'
        )
        return jsonify({
            'success': True, 
            'name': user_record['name'], 
            'token': token,
            'has_preferences': has_preferences
        })
    
    conn.close()
    return jsonify({'success': False, 'message': '密码错误'}), 401
    
@app.route('/api/verify', methods=['GET'])
@token_required
def verify(current_user):
    conn = get_db_connection()
    user = conn.execute('SELECT name FROM users WHERE username=?', (current_user,)).fetchone()
    conn.close()
    if user:
        return jsonify({'success': True, 'name': user['name']})
    return jsonify({'success': False, 'message': '用户不存在'}), 404

# ================= API (首页内容) =================
# 2. 修改 /api/recommend 接口逻辑
@app.route('/api/recommend', methods=['GET'])
def recommend():
    conn = get_db_connection()
    cursor = conn.cursor()      # 创建游标对象

    if not current_username:
        # 随机获取6条景点记录
        recs = conn.execute('SELECT * FROM scenic_spots ORDER BY RANDOM() LIMIT 6').fetchall()
        print("no user mode")
    else:
        user_id = get_user_id_from_username(current_username)
        interests = get_translated_interests(user_id)
        search_res = search_engine.search(interests, top_k=6)
        spot_ids = [item["attraction_id"] for item in search_res]
        placeholders = ", ".join("?" for _ in spot_ids)
        cursor.execute(f"""
            SELECT id, full_name, city, district, info as description,
                likes, comment_count, collect_count
            FROM scenic_spots
            WHERE id IN ({placeholders})
            ORDER BY likes DESC
            """, spot_ids)
        recs = [dict(row) for row in cursor.fetchall()]
        print("user mode")
    # recs = conn.execute('SELECT * FROM scenic_spots ORDER BY RANDOM() LIMIT 6').fetchall()

    conn.close()
    
    # 关键：处理二进制字段（如图片数据），转为JSON可序列化的base64字符串
    processed_recs = []
    for rec in recs:
        spot_dict = dict(rec)  # 将 sqlite3.Row 转为字典
        # 遍历所有字段，检查并转换bytes类型
        for key, value in spot_dict.items():
            if isinstance(value, bytes):
                # 二进制转base64字符串
                spot_dict[key] = base64.b64encode(value).decode('utf-8')
        processed_recs.append(spot_dict)
    
    # 返回处理后的数据
    return jsonify({'success': True, 'data': processed_recs})

# 【已修改】使用 Valid.py 的真值算法重构游记排名逻辑 (简化版，移除作者信息)
@app.route('/api/rank', methods=['GET'])
def rank():
    try:
        conn = get_db_connection()
        
        # 1. 只读取 travel_notes 表
        notes_df = pd.read_sql("SELECT * FROM travel_notes;", conn)
        conn.close()
        
        # 如果没有任何游记，直接返回空列表
        if notes_df.empty:
            return jsonify({'success': True, 'data': []})

        # 2. 运行你的真值算法
        # 2.1 社交特征计算
        for col in ['like_count','collect_count','comment_count','share_count']:
            if col not in notes_df.columns:
                notes_df[col] = 0
            notes_df[col] = pd.to_numeric(notes_df[col], errors="coerce").fillna(0)

        notes_df['social_raw'] = (notes_df['like_count'] + notes_df['collect_count'] + notes_df['comment_count'] + notes_df['share_count']).apply(lambda x: math.sqrt(x+1))
        
        social_raw_min = notes_df['social_raw'].min()
        social_raw_max = notes_df['social_raw'].max()
        # 避免分母为0的情况
        if (social_raw_max - social_raw_min) == 0:
            notes_df['social_norm'] = 0.0
        else:
            notes_df['social_norm'] = (notes_df['social_raw'] - social_raw_min) / (social_raw_max - social_raw_min)

        # 2.2 文本特征计算
        notes_df['text_combined'] = notes_df.get('title',"").astype(str) + " " + notes_df.get('description',"").astype(str)
        notes_df['text_clean'] = notes_df['text_combined'].apply(clean_text)
        notes_df['sentiment'] = notes_df['text_clean'].apply(sentiment_score)
        notes_df['text_score'] = notes_df.apply(compute_text_score, axis=1)

        # 2.3 计算最终真值分数
        w_social, w_text = 0.4, 0.6
        notes_df['TruthScore'] = w_social * notes_df['social_norm'] + w_text * notes_df['text_score']
        
        # 3. 排序并选取Top 10 (不再合并作者信息)
        top_10_notes = notes_df.sort_values("TruthScore", ascending=False).head(10)
        
        # 4. 格式化输出
        output_cols = ['id', 'title', 'description', 'TruthScore', 'like_count', 'collect_count']
        result_list = top_10_notes[output_cols].to_dict('records')

        return jsonify({'success': True, 'data': result_list})

    except Exception as e:
        print(f"Error in /api/rank: {e}")
        return jsonify({'success': False, 'message': f'计算排名时发生错误: {str(e)}'}), 500

# ================= API (景点交互) =================
@app.route('/api/spots/<int:spot_id>', methods=['GET'])
def get_spot_details(spot_id):
    conn = get_db_connection()
    spot = conn.execute('SELECT * FROM scenic_spots WHERE id = ?', (spot_id,)).fetchone()
    
    if not spot:
        conn.close()
        return jsonify({'success': False, 'message': '景点不存在'}), 404

    spot_dict = dict(spot)
    for key in spot_dict:
        if isinstance(spot_dict[key], bytes):
            # 将二进制数据转换为 base64 字符串
            spot_dict[key] = base64.b64encode(spot_dict[key]).decode('utf-8')
    user = get_user_from_token()

    if user:
        user_id = user['id']
        liked = conn.execute('SELECT 1 FROM spot_likes WHERE user_id = ? AND spot_id = ?', (user_id, spot_id)).fetchone()
        collected = conn.execute('SELECT 1 FROM spot_collections WHERE user_id = ? AND spot_id = ?', (user_id, spot_id)).fetchone()
        spot_dict['user_has_liked'] = bool(liked)
        spot_dict['user_has_collected'] = bool(collected)
    else:
        spot_dict['user_has_liked'] = False
        spot_dict['user_has_collected'] = False
        
    conn.close()
    return jsonify({'success': True, 'data': spot_dict})

@app.route('/api/spots/<int:spot_id>/like', methods=['POST'])
@token_required
def toggle_like_spot(current_user, spot_id):
    user = get_user_by_username(current_user)
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 404
    user_id = user['id']
    
    conn = get_db_connection()
    try:
        existing_like = conn.execute('SELECT id FROM spot_likes WHERE user_id = ? AND spot_id = ?', (user_id, spot_id)).fetchone()
        if existing_like:
            conn.execute('DELETE FROM spot_likes WHERE id = ?', (existing_like['id'],))
            conn.execute('UPDATE scenic_spots SET likes = likes - 1 WHERE id = ? AND likes > 0', (spot_id,))
            message = '取消点赞成功'
            liked = False
        else:
            conn.execute('INSERT INTO spot_likes (user_id, spot_id) VALUES (?, ?)', (user_id, spot_id))
            conn.execute('UPDATE scenic_spots SET likes = likes + 1 WHERE id = ?', (spot_id,))
            message = '点赞成功'
            liked = True
        
        conn.commit()
        spot = conn.execute('SELECT likes FROM scenic_spots WHERE id = ?', (spot_id,)).fetchone()
        return jsonify({'success': True, 'message': message, 'liked': liked, 'like_count': spot['likes'] if spot else 0})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'message': f'操作失败: {str(e)}'}), 500
    finally:
        conn.close()

@app.route('/api/spots/<int:spot_id>/collect', methods=['POST'])
@token_required
def toggle_collect_spot(current_user, spot_id):
    user = get_user_by_username(current_user)
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 404
    user_id = user['id']
    
    conn = get_db_connection()
    try:
        existing_collection = conn.execute('SELECT id FROM spot_collections WHERE user_id = ? AND spot_id = ?', (user_id, spot_id)).fetchone()
        if existing_collection:
            conn.execute('DELETE FROM spot_collections WHERE id = ?', (existing_collection['id'],))
            conn.execute('UPDATE scenic_spots SET collect_count = collect_count - 1 WHERE id = ? AND collect_count > 0', (spot_id,))
            message = '取消收藏成功'
            collected = False
        else:
            conn.execute('INSERT INTO spot_collections (user_id, spot_id) VALUES (?, ?)', (user_id, spot_id))
            conn.execute('UPDATE scenic_spots SET collect_count = collect_count + 1 WHERE id = ?', (spot_id,))
            message = '收藏成功'
            collected = True
            
        conn.commit()
        spot = conn.execute('SELECT collect_count FROM scenic_spots WHERE id = ?', (spot_id,)).fetchone()
        return jsonify({'success': True, 'message': message, 'collected': collected, 'collect_count': spot['collect_count'] if spot else 0})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'message': f'操作失败: {str(e)}'}), 500
    finally:
        conn.close()
        
# ================= API (搜索) =================
@app.route('/api/search', methods=['GET'])
def search():
    keyword = request.args.get("q", "").strip()
    if not keyword:
        return jsonify({"success": False, "message": "请输入搜索关键词"})
    
    user = get_user_from_token()
    user_id = user['id'] if user else None

    conn = get_db_connection()
    cursor = conn.cursor()  # 定义cursor变量
    
    spots = conn.execute("""
        SELECT id, full_name, city, district, info as description, 
               likes, comment_count, collect_count
        FROM scenic_spots 
        WHERE full_name LIKE ? OR info LIKE ? OR city LIKE ?
        ORDER BY likes DESC
        LIMIT 10
    """, (f"%{keyword}%", f"%{keyword}%", f"%{keyword}%")).fetchall()

    if len(spots) <= 0:
            search_res = search_engine.search(keyword, top_k=10)
            if search_res:
                spot_ids = [item["attraction_id"] for item in search_res]
                placeholders = ", ".join("?" for _ in spot_ids)
                cursor.execute(f"""
                    SELECT id, full_name, city, district, info as description,
                        likes, comment_count, collect_count
                    FROM scenic_spots
                    WHERE id IN ({placeholders})
                    ORDER BY likes DESC
                """, spot_ids)
                spots = [dict(row) for row in cursor.fetchall()]
    elif len(spots) < 10:
        search_res = search_engine.search(keyword, top_k=10-len(spots))
        if search_res:
            spot_ids = [item["attraction_id"] for item in search_res]
            placeholders = ", ".join("?" for _ in spot_ids)
            cursor.execute(f"""
                SELECT id, full_name, city, district, info as description,
                    likes, comment_count, collect_count
                FROM scenic_spots
                WHERE id IN ({placeholders})
                ORDER BY likes DESC
            """, spot_ids)
            spots.extend([dict(row) for row in cursor.fetchall()])


    if user_id:
        notes_query = """
            SELECT tn.id, tn.title, tn.description as content, tn.like_count, tn.collect_count, 
                   u.name as author_name,
                   CASE WHEN nl.user_id IS NOT NULL THEN 1 ELSE 0 END as user_has_liked,
                   CASE WHEN nc.user_id IS NOT NULL THEN 1 ELSE 0 END as user_has_collected
            FROM travel_notes tn
            JOIN users u ON tn.author_id = u.id
            LEFT JOIN note_likes nl ON tn.id = nl.note_id AND nl.user_id = ?
            LEFT JOIN note_collections nc ON tn.id = nc.note_id AND nc.user_id = ?
            WHERE tn.title LIKE ? OR tn.description LIKE ?
            ORDER BY tn.like_count DESC, tn.crawl_time DESC
            LIMIT 10
        """
        notes = conn.execute(notes_query, (user_id, user_id, f"%{keyword}%", f"%{keyword}%")).fetchall()
    else:
        notes_query = """
            SELECT tn.id, tn.title, tn.description as content, tn.like_count, tn.collect_count,
                   u.name as author_name,
                   0 as user_has_liked, 0 as user_has_collected
            FROM travel_notes tn
            JOIN users u ON tn.author_id = u.id
            WHERE tn.title LIKE ? OR tn.description LIKE ?
            ORDER BY tn.like_count DESC, tn.crawl_time DESC
            LIMIT 10
        """
        notes = conn.execute(notes_query, (f"%{keyword}%", f"%{keyword}%")).fetchall()

    conn.close()
    
    return jsonify({
        "success": True, 
        "data": {
            "spots": [dict(spot) for spot in spots],
            "notes": [dict(note) for note in notes]
        }
    })

# ================= API (游记交互) =================


@app.route('/api/notes/<int:note_id>', methods=['GET'])
def get_note_details(note_id):
    conn = get_db_connection()
    
    # 联合查询 travel_notes 和 users 表，获取作者名
    query = """
        SELECT tn.id, tn.title, tn.description, tn.like_count, tn.collect_count, u.name as author_name
        FROM travel_notes tn
        JOIN users u ON tn.author_id = u.id
        WHERE tn.id = ?
    """
    note = conn.execute(query, (note_id,)).fetchone()

    if not note:
        conn.close()
        return jsonify({'success': False, 'message': '游记不存在'}), 404

    note_dict = dict(note)

    # 检查当前登录用户是否已点赞或收藏
    user = get_user_from_token()
    if user:
        user_id = user['id']
        liked = conn.execute('SELECT 1 FROM note_likes WHERE user_id = ? AND note_id = ?', (user_id, note_id)).fetchone()
        collected = conn.execute('SELECT 1 FROM note_collections WHERE user_id = ? AND note_id = ?', (user_id, note_id)).fetchone()
        note_dict['user_has_liked'] = bool(liked)
        note_dict['user_has_collected'] = bool(collected)
    else:
        note_dict['user_has_liked'] = False
        note_dict['user_has_collected'] = False
        
    conn.close()
    return jsonify({'success': True, 'data': note_dict})

@app.route('/api/notes/<int:note_id>/like', methods=['POST'])
@token_required
def toggle_like_note(current_user, note_id):
    user = get_user_by_username(current_user)
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 404
    user_id = user['id']

    conn = get_db_connection()
    try:
        existing_like = conn.execute('SELECT id FROM note_likes WHERE user_id = ? AND note_id = ?', (user_id, note_id)).fetchone()

        if existing_like:
            conn.execute('DELETE FROM note_likes WHERE id = ?', (existing_like['id'],))
            conn.execute('UPDATE travel_notes SET like_count = like_count - 1 WHERE id = ? AND like_count > 0', (note_id,))
            message = '取消点赞成功'
            liked = False
        else:
            conn.execute('INSERT INTO note_likes (user_id, note_id) VALUES (?, ?)', (user_id, note_id))
            conn.execute('UPDATE travel_notes SET like_count = like_count + 1 WHERE id = ?', (note_id,))
            message = '点赞成功'
            liked = True
        
        conn.commit()
        note = conn.execute('SELECT like_count FROM travel_notes WHERE id = ?', (note_id,)).fetchone()
        return jsonify({'success': True, 'message': message, 'liked': liked, 'like_count': note['like_count'] if note else 0})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'message': f'操作失败: {str(e)}'}), 500
    finally:
        conn.close()

@app.route('/api/notes/<int:note_id>/collect', methods=['POST'])
@token_required
def toggle_collect_note(current_user, note_id):
    user = get_user_by_username(current_user)
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 404
    user_id = user['id']

    conn = get_db_connection()
    try:
        existing_collection = conn.execute('SELECT id FROM note_collections WHERE user_id = ? AND note_id = ?', (user_id, note_id)).fetchone()
        if existing_collection:
            conn.execute('DELETE FROM note_collections WHERE id = ?', (existing_collection['id'],))
            conn.execute('UPDATE travel_notes SET collect_count = collect_count - 1 WHERE id = ? AND collect_count > 0', (note_id,))
            message = '取消收藏成功'
            collected = False
        else:
            conn.execute('INSERT INTO note_collections (user_id, note_id) VALUES (?, ?)', (user_id, note_id))
            conn.execute('UPDATE travel_notes SET collect_count = collect_count + 1 WHERE id = ?', (note_id,))
            message = '收藏成功'
            collected = True
        
        conn.commit()
        note = conn.execute('SELECT collect_count FROM travel_notes WHERE id = ?', (note_id,)).fetchone()
        return jsonify({'success': True, 'message': message, 'collected': collected, 'collect_count': note['collect_count'] if note else 0})
    except Exception as e:
        conn.rollback()
        return jsonify({'success': False, 'message': f'操作失败: {str(e)}'}), 500
    finally:
        conn.close()

# ================= API (用户中心) =================
@app.route('/api/preferences', methods=['POST'])
@token_required
def save_preferences(current_user):
    data = request.get_json()
    conn = get_db_connection()
    
    try:
        user = conn.execute('SELECT id FROM users WHERE username = ?', (current_user,)).fetchone()
        if user:
            user_id = user['id']
            
            profile = conn.execute('SELECT id FROM user_preferences WHERE user_id = ?', (user_id,)).fetchone()
            
            if profile:
                conn.execute('UPDATE user_preferences SET preferences = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ?', 
                             (json.dumps(data), user_id))
            else:
                conn.execute('INSERT INTO user_preferences (user_id, preferences) VALUES (?, ?)', 
                             (user_id, json.dumps(data)))
            
            conn.commit()
            return jsonify({'success': True, 'message': '偏好设置已保存'})
        else:
            return jsonify({'success': False, 'message': '用户不存在'}), 404
    except Exception as e:
        conn.rollback()
        print(f"Error saving preferences: {e}") 
        return jsonify({'success': False, 'message': f'保存失败: {str(e)}'}), 500
    finally:
        conn.close()

@app.route('/api/user/stats', methods=['GET'])
@token_required
def get_user_stats(current_user):
    user = get_user_by_username(current_user)
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 404
    user_id = user['id']

    conn = get_db_connection()
    total_likes_received = conn.execute('SELECT SUM(like_count) as total FROM travel_notes WHERE author_id = ?', (user_id,)).fetchone()['total'] or 0
    total_collections_made = conn.execute('SELECT COUNT(id) as total FROM spot_collections WHERE user_id = ?', (user_id,)).fetchone()['total'] or 0
    total_notes_posted = conn.execute('SELECT COUNT(id) as total FROM travel_notes WHERE author_id = ?', (user_id,)).fetchone()['total'] or 0
    conn.close()

    return jsonify({
        'success': True,
        'data': {
            'name': user['name'],
            'total_likes_received': total_likes_received,
            'total_collections_made': total_collections_made,
            'total_notes_posted': total_notes_posted,
        }
    })

@app.route('/api/user/collections', methods=['GET'])
@token_required
def get_user_collections(current_user):
    user = get_user_by_username(current_user)
    if not user:
        return jsonify({'success': False, 'message': '用户不存在'}), 404
    user_id = user['id']
    conn = get_db_connection()

    spots = conn.execute('''
        SELECT ss.id, ss.full_name, ss.description, ss.info, ss.likes
        FROM spot_collections sc
        JOIN scenic_spots ss ON sc.spot_id = ss.id
        WHERE sc.user_id = ?
        ORDER BY sc.created_at DESC
    ''', (user_id,)).fetchall()
    conn.close()

    return jsonify({'success': True, 'data': [dict(spot) for spot in spots]})

@app.route('/api/get_username', methods=['POST'])
def get_username():
    data = request.get_json()
    username = data.get('username')
    if username:
        print(f"前端传递的用户名：{username}")
        global current_username
        current_username = username
        print(f"current username:{current_username}")
        return jsonify({"status": "success", "username": username})
    return jsonify({"status": "error", "message": "未获取到用户名"})

# ================= 启动 =================
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)